package org.lemon.transport.coap.server.service;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.CoapServer;
import org.lemon.transport.coap.client.CoapClientContext;
import org.lemon.transport.coap.server.service.resource.CoapTransportResource;
import org.lemon.transport.coap.server.service.resource.OtaPackageTransportResource;
import org.lemon.transport.context.data.ota.OtaPackageType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.UnknownHostException;

@Slf4j
@Service
public class CoapTransportService {

    @Autowired
    private CoapService coapService;

    @Autowired
    private CoapTransportContext transportContext;

    @Autowired
    private CoapClientContext clientContext;

    private CoapServer coapServer;

    @PostConstruct
    public void init() throws UnknownHostException {

        log.info("Starting Coap transport server...");
        this.coapServer = coapService.getCoapServer();
        CoapResource api = new CoapResource("api");
        api.add(new CoapTransportResource("v1",
                transportContext,
                coapService,
                clientContext));
        coapServer.add(api);

        //{OtaPackageType}/{accessToken}?title=&version=&size&chunk=
        coapServer.add(new OtaPackageTransportResource(OtaPackageType.FIRMWARE, transportContext,
                coapService));
        coapServer.add(new OtaPackageTransportResource(OtaPackageType.SOFTWARE, transportContext,
                coapService));
        log.info("CoAP transport started!");
    }

    @PreDestroy
    public void shutdown() {
        this.coapServer.destroy();
        log.info("Coap transport server stopped!");
    }
}
